import { messages, queryCurrencyPrecision } from "share/common";
import React from 'react';
import { connect } from 'react-redux';
import errorMessage from 'share/errorMessage';
import menuRoute from 'routes/menuRoute'
import { message, Button, Popconfirm, Icon, Row, Col, Badge, Popover } from 'antd';
import ResizeTable from 'components/resize-table'
import SlideFrame from 'components/slide-frame'
import NewScene from 'containers/expense-reimbursement-control/expense-standard/travel-policy/new-scene'
import NewRule from 'containers/expense-reimbursement-control/expense-standard/travel-policy/new-rule'
import travelPolicyService from 'containers/expense-reimbursement-control/expense-standard/travel-policy/travel-policy.service'
import 'styles/custom-fields.scss'

class SceneDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      scene: {}, //用餐类型详情
      showSlideFrame: false, //编辑用餐类型的侧拉框是否弹出
      nowScene: {}, //编辑用餐类型的侧拉框里所用的参数
      page: 0,
      pageSize: 10,
      pagination: {
        current: 0,
        total: 0
      },
      data: [], //该用餐类型下的差标列表
      loading: false,
      columns: [
        {title: messages('common.sequence'), dataIndex: 'index', width: '5%', render: (value, record, index) => index + 1 + this.state.pageSize * this.state.page}, //序号
        {title: messages('expense-reimbursement-control.key108')/*用餐标准*/, dataIndex: 'comment', width: '15%'},
        {title: messages('setting.key1187'/*适用人群*/), dataIndex: 'travelRuleRelations', width: '15%',
          render: (value, record) => (
            this.renderUser(value, record)
          )
        }, //适用人群
        {title: messages('expense-reimbursement-control.key54')/*适用公司*/, dataIndex: 'travelRuleCompanyList', width: '15%',
          render: (value, record) => (
            this.renderCompany(value, record)
          )
        }, //适用公司
        {title: messages('common.currency')/*币种*/, dataIndex: 'amount', width: '5%', render: value => (<span>CNY</span>)}, //币种
        {title: messages('common.amount')/*金额*/, dataIndex: 'travelRuleConditions', width: '10%', align: "right",
          render: (value, record) => (
            this.renderCurrencyAndAmount(value, record)
          )
        }, //金额
        {title: messages('common.column.status'), dataIndex: 'status', width: '10%', align: "right",
          render: (value,record) => (
            <Badge
              status={value === 1001 ? 'success' : 'error'}
              text={value === 1001 ? messages('common.enabled') : messages('common.disabled')}
            />
          )
        }, //状态
        {title: messages('common.operation'), dataIndex: 'operation', key: 'operation',"align":"center",
          render: (text, record) => (
            <span>
              <a onClick={(e) => this.handleEditStandard(e, record)}>{messages('common.edit')}</a>
              <span className="ant-divider"/>
              <a onClick={(e) => this.handleEditStandard(e, record, true)}>{messages('setting.key1188'/*复制并编辑*/)}</a>
              <span className="ant-divider"/>
              <Popconfirm onConfirm={(e) => this.handleDelete(e, record)} title={messages('setting.key1189'/*你确认要删除？*/)}>{/* 你确定要删除organizationName吗 */}
                <a onClick={(e) => {e.preventDefault();e.stopPropagation();}}>{messages('common.delete')}</a>
              </Popconfirm>
            </span>
          )
        },  //操作
      ],
      showStandardSlideFrame: false, //编辑用餐标准的侧拉框是否弹出
      nowStandard: {}
    };
  }

  componentDidMount(){
    this.getSceneDetail();
    this.getStandardList();
  }

  getSceneDetail = () => {
    const { params } = this.props;
    travelPolicyService.getSceneDetail(params.sceneId).then(res => {
      this.setState({scene: res.data});
    }).catch(e => {
      errorMessage(e.response);
    });
  };

  //获取该用餐类型下的用餐的差旅标准
  getStandardList = () => {
    const { params } = this.props;
    const { page, pageSize } = this.state;
    this.setState({loading: true});
    travelPolicyService.getStandardList(page, pageSize, params.sceneId).then(res => {
      this.setState({
        data: res.data,
        loading: false,
        pagination: {
          current: page + 1,
          total: Number(res.headers['x-total-count']),
          onChange: this.onChangePager
        }
      });
    }).catch(e => {
      this.setState({loading: false});
      errorMessage(e.response);
    });
  };

  //点击分页
  onChangePager = (page) => {
    const { page: currentPage } = this.state;
    if (page - 1 !== currentPage) {
      this.setState({page: page - 1}, this.getStandardList);
    }
  };

  renderVisibleForms = () => {
    const { scene } = this.state;
    let visibleFormNameList = [];
    scene.visibleForms && scene.visibleForms.map(form => {
      visibleFormNameList.push(form.formName);
    });
    return visibleFormNameList.join(', ');
  };

  handleBack = () => {
    window.history.go(-1);
  };

  handleOnClose = () => {
    this.setState({
      showSlideFrame: false,
      nowScene: {
        showSlideFrame: false
      }
    });
  };

  //isSuccess是否是保存成功的关闭，如果是，则要刷新用餐类型详情
  handleCloseSlide = (isSuccess) => {
    isSuccess && this.getSceneDetail();
    this.setState({
      showSlideFrame: false,
      nowScene: {
        showSlideFrame: false
      }
    });
  };

  //编辑
  handleEdit = () => {
    const { params } = this.props;
    const { scene } = this.state;
    this.setState({
      showSlideFrame: true,
      nowScene: {
        showSlideFrame: true,
        id: params.id,
        setOfBooksId: params.setOfBooksId,
        travelItineraryStandID: params.travelItineraryStandID,
        record: JSON.parse(JSON.stringify(scene))
      }
    });
  };

  //表格渲染适用人群
  renderUser = (value, record) => {
    if (value[0].type === 1001){
      return <span>{messages('setting.key1037'/*通用*/)}</span>
    }else {
      let relationNameList = [];
      if (value) {
        value.map((item, index) => {
          if (item.relationOID) {
            relationNameList.push(item.relationName);
          }
        });
      }
      return <Popover placement="topLeft" content={relationNameList.join(',')}>{relationNameList.join(',')}</Popover>
    }
  };

  //表格渲染适用公司
  renderCompany = (value, record) => {
    if (value && value.length) {
      let relationNameList = [];
      if (value) {
        value.map((item, index) => {
          if (item.companyId) {
            relationNameList.push(item.companyName);
          }
        });
      }
      return <Popover placement="topLeft" content={relationNameList.join(',')}>{relationNameList.join(',')}</Popover>
    } else {
      return <span>{messages('setting.key1037'/*通用*/)}</span>
    }
  };

  //表格渲染金额
  renderCurrencyAndAmount = (value, record) => {
    let currency = '';
    let amount = 0;
    if (value && value.length) {
      value.map((item, index) => {
        if (item.name === 'currency') {
          currency = item.value;
        }
        if (item.name === 'amount') {
          amount = item.value;
        }
      });
    }
    return <span>{this.filterMoney(amount, queryCurrencyPrecision(currency))}</span>
  };

  handleOnCloseStandard = () => {
    const { nowStandard } = this.state;
    nowStandard.showSlideFrame = false;
    this.setState({
      nowStandard,
      showStandardSlideFrame: false
    });
  };

  //isSuccess是否是保存成功的关闭，如果是，则要刷新用餐类型的差标列表
  handleCloseSlideStandard = (isSuccess) => {
    const { nowStandard } = this.state;
    nowStandard.showSlideFrame = false;
    isSuccess && this.getStandardList();
    this.setState({
      nowStandard,
      showStandardSlideFrame: false
    });
  };

  handleNewStandard = () => {
    const { params } = this.props;
    this.setState({
      showStandardSlideFrame: true,
      nowStandard: {
        showSlideFrame: true,
        isNew: true,
        type: 'standard',
        id: params.id,
        setOfBooksId: params.setOfBooksId,
        travelItineraryStandID: params.travelItineraryStandID,
        sceneId: params.sceneId
      }
    });
  };

  //isCopy 是否是复制的编辑
  handleEditStandard = (e, record, isCopy) => {
    const { params } = this.props;
    this.setState({
      showStandardSlideFrame: true,
      nowStandard: {
        showSlideFrame: true,
        isNew: isCopy,
        type: 'standard',
        id: params.id,
        setOfBooksId: params.setOfBooksId,
        travelItineraryStandID: params.travelItineraryStandID,
        sceneId: params.sceneId,
        record: record
      }
    });
  };

  //删除用餐差旅标准
  handleDelete = (e, record) => {
    this.setState({loading: true});
    travelPolicyService.deleteTravelStandardRule(record.id).then((resp) => {
      if (resp.status === 200){
        this.setState({loading: false});
        message.success(messages('setting.key213'/*删除成功*/));
        this.getStandardList();
      }
    }).catch((e) => {
      this.setState({loading: false});
      errorMessage(e.response);
    });
  };

  render() {
    const { scene, showSlideFrame, nowScene, columns, data, pagination, loading, showStandardSlideFrame, nowStandard } = this.state;
    return (
      <div>
        <div className="header-title">
          {messages('expense-reimbursement-control.key98')/*用餐类型*/}
          <span className='default-color-font' style={{fontSize: 12, display: 'inline-block', marginLeft: 20, cursor: 'pointer'}} onClick={this.handleEdit}>
            {messages('common.edit'/*编辑*/)}
          </span>
        </div>
        <Row className="custom-form-row">
          <Col span={8}>
            <div className="field-name">{messages('expense-reimbursement-control.key103')/*类型名称*/}</div>
            <div className="field-content">{scene.name}</div>
          </Col>
          <Col span={8}>
            <div className="field-name">{messages('common.column.status')/*状态*/}</div>
            <div className="field-content">{scene.status === 1 ? messages('common.enabled') : messages('common.disabled')}</div>
          </Col>
          <Col span={8}>
            <div className="field-name">{messages('expense-reimbursement-control.key104')/*可用时段*/}</div>
            {scene.durationType && (
              <div className="field-content">
                {scene.durationType === 1 ? messages('expense-reimbursement-control.key105')/*全天*/ : `${scene.startTime} - ${scene.endTime}`}
              </div>
            )}
          </Col>
        </Row>
        <Row className="custom-form-row">
          <Col span={8}>
            <div className="field-name">{messages('expense-reimbursement-control.key99')/*适用表单*/}</div>
            <div className="field-content">{scene.visibleFormScope === 1 ? messages('expense-reimbursement-control.key28')/*通用*/ : this.renderVisibleForms()}</div>
          </Col>
        </Row>
        <SlideFrame
          content={NewScene}
          title={messages('expense-reimbursement-control.key98')/*用餐类型*/}
          show={showSlideFrame}
          onClose={this.handleOnClose}
          afterClose={this.handleCloseSlide}
          params={nowScene}
        />
        <div style={{background: '#F0F2F5', height: 10, margin: '20px -20px'}}></div>
        <div className="header-title">
          {messages('expense-reimbursement-control.key108')/*用餐标准*/}
        </div>
        <Button type="primary" style={{marginBottom: 24}} onClick={this.handleNewStandard}>{messages('expense-reimbursement-control.key50')/*新增*/}</Button>
        <ResizeTable
          columns={columns}
          dataSource={data}
          pagination={pagination}
          loading={loading}
          rowKey={record => record.id}
          bordered
          size="middle"
        />
        <SlideFrame
          content={NewRule}
          title={messages('expense-reimbursement-control.key108')/*用餐标准*/}
          show={showStandardSlideFrame}
          onClose={this.handleOnCloseStandard}
          afterClose={this.handleCloseSlideStandard}
          params={nowStandard}
        />
        <a style={{fontSize:'14px', display: 'inline-block', marginTop: 10}} onClick={this.handleBack}>
          <Icon type="rollback" style={{marginRight:'5px'}}/>{messages('common.back')}
        </a>
      </div>
    )
  }
}

SceneDetail.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    tenantMode: state.main.tenantMode
  }
}

SceneDetail.propTypes = {};

SceneDetail.defaultProps = {};

export default connect(mapStateToProps)(SceneDetail);
